//
//  QRCodeViewController.swift
//  XMGWB
//
//  Created by 1 on 16/1/8.
//  Copyright © 2016年 xiaomage. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {
    // MARK:- 属性
    @IBOutlet weak var tabBar: UITabBar!
    @IBOutlet weak var scanView: UIImageView!
    @IBOutlet weak var containerView: UIView!
      @IBOutlet weak var borderView: UIImageView!
    @IBOutlet weak var resultLabel: UILabel!
    
    @IBOutlet weak var containerViewHCon: NSLayoutConstraint!
    @IBOutlet weak var scanViewTopCons: NSLayoutConstraint!

    // MARK: 自定义的属性
    var previewLayer : AVCaptureVideoPreviewLayer?
    var shapeLayer : CAShapeLayer?

    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tabBar.delegate = self
        // 让tabBar默认选中第0个
        tabBar.selectedItem = tabBar.items![0]
        //设置扫描动画 
        setupScanAnimation()
        
        startScanning()
    }
    
    // MARK:- 自定义的函数
    private func startScanning() {
        // 1.创建捕捉会话
        let session = AVCaptureSession()
        
        // 2.添加输入(摄像头)
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        guard let input = try? AVCaptureDeviceInput(device: device) else {
            CBWLog("没有输入设备")
            return
        }
        session.addInput(input)
        
        // 3.添加输出(metadata方式输入)
        let output = AVCaptureMetadataOutput()
        output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
        session.addOutput(output)
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        let x = containerView.frame.origin.y / view.frame.size.height
        let y = containerView.frame.origin.x / view.frame.size.width
        let width = borderView.frame.size.height / view.frame.size.height
        let height = borderView.frame.size.width / view.frame.size.width
        output.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)
        
        print(borderView.frame)
        
        // 4.添加预览图层
        let previewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.frame = view.bounds
        view.layer.insertSublayer(previewLayer, atIndex: 0)
        self.previewLayer = previewLayer
        
        // 5.开始扫描
        session.startRunning()
    }
    
    // MARK:- 事件监听
    @IBAction func close(sender: AnyObject) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @IBAction func photoItemClick(sender: AnyObject) {
        // 1.判断照片源是否可用
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            print("照片库不可用")
            return
        }
        
        // 2.创建选择照片的控制器
        let ipc = UIImagePickerController()
        
        // 3.设置照片源
        ipc.sourceType = .PhotoLibrary
        
        // 4.设置代理
        ipc.delegate = self
        
        // 5.弹出控制器
        presentViewController(ipc, animated: true, completion: nil)
    }

    }

extension QRCodeViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        // 1.拿到图片
        guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
            print("没有获取到照片")
            return
        }
        
        // 2.识别照片中二维码的信息
        getQRCodeInfo(image)
        
        // 3.退出控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

    // MARK:=============== 扫描动画 ===============
    private func setupScanAnimation() {
        // 1.让扫描View在最上面
        scanViewTopCons.constant = -containerViewHCon.constant
        view.layoutIfNeeded()
        
        // 2.执行扫描动画
        UIView.animateWithDuration(1.5) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanViewTopCons.constant = self.containerViewHCon.constant
            self.view.layoutIfNeeded()
        }
    }
    /// 识别图像中的二维码
    private func getQRCodeInfo(image : UIImage) {
        // 1.创建扫描器
        let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: nil)
        
        // 2.扫描结果
        guard let ciImage = CIImage(image: image) else {
            print("转ciImage失败")
            return
        }
        let features = detector.featuresInImage(ciImage)
        
        // 3.遍历扫描结果
        for f in features {
            guard let feature = f as? CIQRCodeFeature else {
                continue
            }
            
            print(feature.messageString)
        }
    }

}

// MARK:- 输入的代理<AVCaptureMetadataOutputObjectsDelegate>
extension QRCodeViewController : AVCaptureMetadataOutputObjectsDelegate {
    /// 拿到输出结果
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        // 1.获取扫描结果
        guard let object = metadataObjects.last as? AVMetadataMachineReadableCodeObject else {
            print("没有获取到扫描结果")
            return
        }
        
        // 2.获取扫描结果并且显示出来
        self.resultLabel.text = object.stringValue
        
        // 3.使用预览图层,将corners的点转成坐标系中的点
        guard let newObject = previewLayer?.transformedMetadataObjectForMetadataObject(object) as? AVMetadataMachineReadableCodeObject else {
            print("没有将corners的点转成坐标系中的点成功")
            return
        }
        
        // 4.画边框
        drawBorder(newObject)
    }
    
    /// 画边框
    private func drawBorder(object : AVMetadataMachineReadableCodeObject) {
        // 0.移除前一个画出的边框
        self.shapeLayer?.removeFromSuperlayer()
        
        // 1.创建CAShapeLayer(形状类型:专门用于画图)
        let shapeLayer = CAShapeLayer()
        
        // 2.设置layer属性
        shapeLayer.strokeColor = UIColor.redColor().CGColor
        shapeLayer.fillColor = UIColor.clearColor().CGColor
        shapeLayer.lineWidth = 2.0
        
        // 3.创建贝塞尔曲线
        let path = UIBezierPath()
        
        // 4.给贝塞尔曲线添加对应的点
        for i in 0..<object.corners.count {
            // 4.1.获取每一个点对应的字典
            let dict = object.corners[i] as! CFDictionary
            var point = CGPointZero
            CGPointMakeWithDictionaryRepresentation(dict, &point)
            
            // 4.2.如果是第一个点,移动到第一个点
            if i == 0 {
                path.moveToPoint(point)
                continue
            }
            
            // 4.3.如果是其他点,则添加点
            path.addLineToPoint(point)
        }
        
        // 5.关闭路径
        path.closePath()
        
        // 6.给shapeLayer设置路径
        shapeLayer.path = path.CGPath
        
        // 7.将layer添加到其他图层中
        previewLayer?.addSublayer(shapeLayer)
        
        // 8.保存layer
        self.shapeLayer = shapeLayer
    }

}



// MARK:- <UITabBarDelegate>
extension QRCodeViewController : UITabBarDelegate {
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        // 1.改变容器视图的高度
        containerViewHCon.constant = item.tag == 0 ? 250 : 150
        view.layoutIfNeeded()
        
        // 2.移除之前动画
        scanView.layer.removeAllAnimations()
        
        // 3.重新开始动画
        setupScanAnimation()
    }
}

